package cn.com.chengmandian.bike.rabbitmq;

import cn.com.chengmandian.bike.model.*;
import cn.com.chengmandian.bike.service.*;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.redis.cache.AgentCacheService;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.com.chengmandian.rabbitmq.constants.RabbitMqConstants;
import cn.com.chengmandian.rabbitmq.pojo.BikePayResult;
import cn.com.chengmandian.service.bike.constants.*;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.math.BigDecimal;

@Slf4j
@Component
public class BikePayReceiver {

    @Autowired
    private IEbMemberPayService memberPayService;

    @Autowired
    private IEbMemberWalletService memberWalletService;

    @Autowired
    private IEbRechargeActivityService rechargeActivityService;

    @Autowired
    private IEbRechargeRecordService rechargeRecordService;

    @Autowired
    private IEbMessageInfoService messageInfoService;

    @Autowired
    private AgentCacheService agentCacheService;

    @Autowired
    private IEbMemberInfoService memberInfoService;

    @Autowired
    private IEbMemberDepositService memberDepositService;

    @Autowired
    private IEbDepositRecordService depositRecordService;

    @Autowired
    private IEbMemberCardService memberCardService;

    @Autowired
    private IEbRideOrderService rideOrderService;

    @Autowired
    private IEbRentOrderService rentOrderService;

    @Autowired
    private IEbRentComboService rentComboService;

    @Autowired
    private IEbRentPenaltyService rentPenaltyService;

    @Autowired
    private IEbMemberComboRecordService memberComboRecordService;

    @Autowired
    private IEbRidePenaltyService ridePenaltyService;

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_WALLET, ackMode = "AUTO")
    public void walletPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            memberWalletService.updateBalance(memberPay.getAreaId(), memberPay.getMemberId(), memberPay.getMoney(), MemberMoneyBusinessTypeEnum.CHARGE, memberPay.getId(), MemberMoneyOperationTypeEnum.USER);
            EbRechargeActivity rechargeActivity = rechargeActivityService.getActivity(memberPay.getAreaId(), memberPay.getMoney());
            String ext = "";
            if (rechargeActivity != null && rechargeActivity.getGiftMoney() != null && rechargeActivity.getGiftMoney().compareTo(new BigDecimal(0)) > 0) {
                memberWalletService.updateBalance(memberPay.getAreaId(), memberPay.getMemberId(), rechargeActivity.getGiftMoney(), MemberMoneyBusinessTypeEnum.ADD_GIFT, rechargeActivity.getId(), MemberMoneyOperationTypeEnum.USER);
                ext = "并额外获得" + rechargeActivity.getGiftMoney().doubleValue() + "元充值礼金，";
                rechargeActivityService.update(new LambdaUpdateWrapper<EbRechargeActivity>()
                        .set(EbRechargeActivity::getTimes, (rechargeActivity.getTimes() + 1))
                        .eq(EbRechargeActivity::getId, rechargeActivity.getId()));
            }
            // 充值记录
            rechargeRecordService.createRecord(memberPay.getId(), memberPay.getAreaId(), memberPay.getMemberId(), rechargeActivity, memberPay.getMoney());
            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 " + DateUtil.now() + " 充值成功" + memberPay.getMoney().doubleValue() + "元，" + ext + "感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.WALLET, null);

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_DEPOSIT, ackMode = "AUTO")
    public void depositPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            memberInfoService.payDeposit(memberPay.getMemberId(), memberPay.getMoney());
            depositRecordService.createRecord(memberPay.getMemberId(), memberPay.getMoney(), memberPay.getId());

            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 " + DateUtil.now() + " 充值押金成功，本次支付" + memberPay.getMoney().doubleValue() + "元，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.DEPOSIT, null);

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_CARD, ackMode = "AUTO")
    public void cardPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            EbMemberCard memberCard = memberCardService.createCard(memberPay.getId(), memberPay.getMemberId(), memberPay.getBusinessId(), memberPay.getMoney(), CommonConstant.ONE, null);
            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 " + DateUtil.now() + " 购买骑行卡成功，本次消费" + memberPay.getMoney().doubleValue() + "元，有效期至 " + DateUtil.format(memberCard.getExpireTime(), "yyyy-MM-dd HH:mm:ss") + " ，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.CARD, memberCard.getId());

            // 通过骑行订单待支付页面 购买骑行卡
            String businessData = memberPay.getBusinessData();
            if(StrUtil.isNotBlank(businessData)) {
                JSONObject jsonBusinessData = JSONObject.parseObject(businessData);
                Integer rideOrderId = jsonBusinessData.getInteger("rideOrderId");
                if(rideOrderId != null) {
                    // 自动消耗购买的骑行开
                    rideOrderService.orderConsumeMemberCard(rideOrderId, memberCard.getId(), UserTypeEnum.MEMBER.getCode());
                }
            }
        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_DEPOSIT_CARD, ackMode = "AUTO")
    public void depositCardPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            EbMemberDeposit memberDeposit = memberDepositService.payCard(memberPay.getMemberId(), memberPay.getBusinessId(), memberPay.getMoney());
            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 " + DateUtil.now() + " 购买免押卡成功，本次支付" + memberPay.getMoney().doubleValue() + "元，有效期至 " + DateUtil.format(memberDeposit.getExpireTime(), "yyyy-MM-dd HH:mm:ss") + " ，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.DEPOSIT_CARD, memberDeposit.getId());

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_RIDE_ORDER, ackMode = "AUTO")
    public void rideOrderPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            rideOrderService.orderPaid(memberPay.getBusinessId(), memberPay.getMoney(), BigDecimal.ZERO, UserTypeEnum.MEMBER.getCode());

            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 " + DateUtil.now() + " 支付骑行订单成功，合计消费" + memberPay.getMoney() + "元 ，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.ORDER, memberPay.getBusinessId());

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_RENT_ORDER, ackMode = "AUTO")
    public void rentOrderPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            // 套餐信息
            EbRentCombo ebRentCombo = rentComboService.getById(memberPay.getBusinessId());
            org.springframework.util.Assert.notNull(ebRentCombo, "识别不到租赁套餐");

            // 生成租赁套餐订单
            rentOrderService.createRecord(memberPay.getMemberId(), memberPay.getId(), memberPay.getPayNo(), memberPay.getAreaId(), memberPay.getMoney(), ebRentCombo);

            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 "  + DateUtil.now() + " 购买租赁套餐"+ebRentCombo.getName()+"成功，支付" + memberPay.getMoney().doubleValue() + "元，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.RENT, null);

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_RENT_PENALTY, ackMode = "AUTO")
    public void rentPenaltyPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            EbRentPenalty rentPenalty = rentPenaltyService.getByPayId(memberPay.getId());
            Assert.notNull(rentPenalty, "租赁罚金信息不存在");

            rentPenaltyService.update(new LambdaUpdateWrapper<EbRentPenalty>()
                    .set(EbRentPenalty::getStatus, RentPenaltyStatusEnum.FINISH_PAY.getCode())
                    .set(EbRentPenalty::getPayTime, DateUtil.date())
                    .eq(EbRentPenalty::getId, rentPenalty.getId()));

            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 "  + DateUtil.now() + " 支付租赁违约金成功" + memberPay.getMoney().doubleValue() + "元，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.RENT, null);

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_MEMBER_COMBO, ackMode = "AUTO")
    public void memberComboPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            EbMemberComboRecord memberComboRecord = memberComboRecordService.createRecord(memberPay.getId(), memberPay.getMemberId(), memberPay.getBusinessId(), memberPay.getMoney());
            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 " + DateUtil.now() + " 购买会员卡成功，本次消费" + memberPay.getMoney().doubleValue() + "元，有效期至 " + DateUtil.format(memberComboRecord.getExpireTime(), "yyyy-MM-dd HH:mm:ss") + " ，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.COMBO, memberComboRecord.getId());

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }

    @RabbitListener(queues = RabbitMqConstants.QUEUE_BIKE_PAY_RIDE_PENALTY, ackMode = "AUTO")
    public void ridePenaltyPay(BikePayResult payResult) {
        try {
            if (payResult == null) {
                log.error("payResult数据为空");
                return;
            }
            log.info("收到支付结果：{}", payResult);

            AgentInfo agentInfo = agentCacheService.getAgent(payResult.getAgentNo());
            LocalMapUtil.setAgentInfo(agentInfo);

            EbMemberPay memberPay = memberPayService.getById(payResult.getMemberPayId());
            Assert.notNull(memberPay, "支付信息不存在");

            ridePenaltyService.paySuccess(memberPay);

            messageInfoService.addSys(memberPay.getMemberId(), MessageChannelEnum.SYS,
                    "尊敬的用户，您于 " + DateUtil.now() + " 缴纳骑行订单罚款，本次支付" + memberPay.getMoney().doubleValue() + "元，感谢您的支持与信任！",
                    null, MessageBusinessTypeEnum.RIDE_PENALTY, memberPay.getBusinessId());

        } catch (Exception e) {
            log.error("处理支付结果错误", e);
        }
    }
}
